package com.tuo51.evaluate.repositories.evaluatev2;

import com.tuo51.evaluate.domain.evaluatingV2.EvaluateV2Question;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@CacheConfig(cacheNames = "EvaluateV2QuestionRepository")
public interface EvaluateV2QuestionRepository extends JpaRepository<EvaluateV2Question, String>, JpaSpecificationExecutor<EvaluateV2Question> {


    @Cacheable(keyGenerator = "keyGenerator")
    @Query(value = "select eq.* from tb_evaluate_question eq " +
            "left join tb_evaluate_item ei on ei.id = eq.itemId " +
            "where eq.id in ( " +
            "select questionId from tb_evaluate_record_answer where recordId = :recordId and checked = false " +
            ") and ei.month = ( " +
            "select min(iei.month) from tb_evaluate_question ieq " +
            "left join tb_evaluate_item iei on iei.id = ieq.itemId " +
            "where ieq.id in ( " +
            "select questionId from tb_evaluate_record_answer where recordId = :recordId and checked = false " +
            ") and iei.dimensionId=ei.dimensionId and advise is not null " +
            ") and advise is not null " +   // and eq.month <= :cMonth
            " order by indexOnPaper", nativeQuery = true)
    List<EvaluateV2Question> findAllFailedQuestion(@Param("recordId") String recordId);

    @Cacheable(keyGenerator = "keyGenerator")
    List<EvaluateV2Question> findAllByItemIdAndDeletedIsFalseOrderByIndexOnPaper(String itemId);

    @Cacheable(keyGenerator = "keyGenerator")
    List<EvaluateV2Question> findAllByOptionGroupAndIndexOnPaperGreaterThanEqualAndDeletedIsFalseOrderByIndexOnPaper(Integer optionGroup, Integer startIndexOnPaper);

    EvaluateV2Question findTopByIndexOnPaperAndDeletedIsFalseOrderByCreated(Integer indexOnPaper);


    @Cacheable(keyGenerator = "keyGenerator")
    List<EvaluateV2Question> findAll();

    @Cacheable(keyGenerator = "keyGenerator")
    EvaluateV2Question getOne(String id);

    @Cacheable(keyGenerator = "keyGenerator")
    EvaluateV2Question getByIndexOnPaperAndDeletedIsFalse(Integer indexOnPaper);

}
